package com.jmgd.cjlx.util;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.StringJoiner;

/**
 * @author kwong
 * 处理http请求基础类
 */
public class HttpClientUtil {
    public static Map doPost(String url, Map<String,String> params, JSONObject jsonData) {
        ////设置超时
        RequestConfig requestconfig = RequestConfig.custom().setConnectionRequestTimeout(10000)
                .setConnectTimeout(10000)
                .setSocketTimeout(60000)
                .build();
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(requestconfig)
                .build();
        HttpPost httppost = new HttpPost(url);
        Map<String,Object> rsMap = new HashMap<String,Object>();
        String rs = "";
        int statusCode = 0;
        try {
            ////设置参数
            ////预设参数
            httppost.setHeader("Connection","keep-alive");
            if(params != null) {
                for(Map.Entry<String,String> entry : params.entrySet()) {
                    httppost.setHeader(entry.getKey(),entry.getValue());
                }
            }
            ////添加数据
            if(jsonData != null) {
                StringEntity requestEntity = new StringEntity(jsonData.toJSONString(), StandardCharsets.UTF_8);
                httppost.setEntity(requestEntity);
            }
            ////执行http接口
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();
                if(entity != null) {
                    rs = EntityUtils.toString(entity,"UTF-8");
                }
            }
            catch (Exception e1) {
                rs = e1.getMessage();
                statusCode = -1;
            } finally {
                response.close();
            }
        }
        catch(Exception e) {
            rs = e.getMessage();
            statusCode = -1;
        } finally {
            try {
                if(httpclient != null) {
                    httpclient.close();
                }
            } catch (IOException e2) {
                rs = e2.getMessage();
                statusCode = -1;
            }
        }
        rsMap.put("statusCode",statusCode);
        if(statusCode == -1) {
            rsMap.put("msg",rs);
            rsMap.put("data",null);
        }
        else {
            rsMap.put("msg","success");
            rsMap.put("data",rs);
        }
        return rsMap;
    }

    public static String doPost2(String url, Map<String,String> headers, String jsonInputString) {
        headers.put("Content-Type", "application/json");
        try {
            // 创建URL对象
            URL urlObj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();

            // 设置请求方法为POST
            con.setRequestMethod("POST");
            con.setDoOutput(true);

            // 设置请求头
            for (Map.Entry<String, String> header : headers.entrySet()) {
                con.setRequestProperty(header.getKey(), header.getValue());
            }

            // 发送JSON数据
            try (OutputStream os = con.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // 处理响应
            int responseCode = con.getResponseCode();
            System.out.println("Response Code: " + responseCode);
            if (responseCode == HttpURLConnection.HTTP_OK) { // success
                try (java.io.BufferedReader br = new java.io.BufferedReader(
                        new java.io.InputStreamReader(con.getInputStream(), "utf-8"))) {
                    StringBuilder response = new StringBuilder();
                    String responseLine;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }
                    System.out.println("Response: " + response.toString());
                    return response.toString();
                }
            } else {
                System.out.println("POST request not worked");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    public static String doPost1(String urlString, String urlParameters) {
        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
            try (OutputStream outputStream = connection.getOutputStream()) {
                outputStream.write(postData);
            }

            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                // 处理 JSON 响应
                String jsonResponse = response.toString();
                System.out.println("Response JSON: " + jsonResponse);

                return jsonResponse;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    public static Map doGet(String url) {
        ////设置超时
        RequestConfig requestconfig = RequestConfig.custom().setConnectionRequestTimeout(10000)
                .setConnectTimeout(10000)
                .setSocketTimeout(60000)
                .build();
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(requestconfig)
                .build();
        HttpGet httpget = new HttpGet(url);
        Map<String,Object> rsMap = new HashMap<String,Object>();
        String rs = "";
        int statusCode = 0;
        try {
            ////设置参数
            ////预设参数
            httpget.setHeader("Connection","keep-alive");
            httpget.setHeader("Content-Type","application/json;charset=UTF-8");
            ////执行http接口
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                HttpEntity entity = response.getEntity();
                if(entity != null) {
                    rs = EntityUtils.toString(entity,"UTF-8");
                }
            }
            catch (Exception e1) {
                rs = e1.getMessage();
                statusCode = -1;
            } finally {
                response.close();
            }
        }
        catch(Exception e) {
            rs = e.getMessage();
            statusCode = -1;
        } finally {
            try {
                if(httpclient != null) {
                    httpclient.close();
                }
            } catch (IOException e2) {
                rs = e2.getMessage();
                statusCode = -1;
            }
        }
        rsMap.put("statusCode",statusCode);
        if(statusCode == -1) {
            rsMap.put("msg",rs);
            rsMap.put("data",null);
        }
        else {
            rsMap.put("msg","success");
            rsMap.put("data",rs);
        }
        return rsMap;
    }


    public static String doGet1(String url,Map<String, String> headers,Map<String, String> params) {
        try {
            // URL 基础地址

            // 查询参数
//            Map<String, String> params = Map.of(
//                    "param1", "value1",
//                    "param2", "value2"
//            );

            // 构建完整的 URL
            StringBuilder urlWithParams = new StringBuilder(url);
            urlWithParams.append("?");
            for (Map.Entry<String, String> entry : params.entrySet()) {
                urlWithParams.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
                urlWithParams.append("=");
                urlWithParams.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
                urlWithParams.append("&");
            }
            // 去掉最后一个 "&"
            if (urlWithParams.charAt(urlWithParams.length() - 1) == '&') {
                urlWithParams.deleteCharAt(urlWithParams.length() - 1);
            }

            URL url1 = new URL(urlWithParams.toString());
            HttpURLConnection connection = (HttpURLConnection) url1.openConnection();

            // 设置请求方法
            connection.setRequestMethod("GET");

            // 请求头
//            Map<String, String> headers = Map.of(
//                    "Accept", "application/json",
//                    "User-Agent", "Mozilla/5.0"
//            );

            for (Map.Entry<String, String> entry : headers.entrySet()) {
                connection.setRequestProperty(entry.getKey(), entry.getValue());
            }

            // 获取响应码
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            // 读取响应
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                // 打印响应
                System.out.println("Response: " + response.toString());
                return response.toString();
            } else {
                System.out.println("GET request not worked, Response Code: " + responseCode);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }



    public static Map doPut(String url, Map<String,String> params, JSONObject jsonData) {
        ////设置超时
        RequestConfig requestconfig = RequestConfig.custom().setConnectionRequestTimeout(10000)
                .setConnectTimeout(10000)
                .setSocketTimeout(60000)
                .build();
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(requestconfig)
                .build();
        HttpPut httpput = new HttpPut(url);
        Map<String,Object> rsMap = new HashMap<String,Object>();
        String rs = "";
        int statusCode = 0;
        try {
            ////设置参数
            ////预设参数
            httpput.setHeader("Connection","keep-alive");
            if(params != null) {
                for(Map.Entry<String,String> entry : params.entrySet()) {
                    httpput.setHeader(entry.getKey(),entry.getValue());
                }
            }
            ////添加数据
            if(jsonData != null) {
                StringEntity requestEntity = new StringEntity(jsonData.toString(), StandardCharsets.UTF_8);
                httpput.setEntity(requestEntity);
            }
            ////执行http接口
            CloseableHttpResponse response = httpclient.execute(httpput);
            try {
                HttpEntity entity = response.getEntity();

                if(entity != null) {
                    rs = EntityUtils.toString(entity,"UTF-8");
                }
            }
            catch (Exception e1) {
                rs = e1.getMessage();
                statusCode = -1;
            } finally {
                response.close();
            }
        }
        catch(Exception e) {
            rs = e.getMessage();
            statusCode = -1;
        } finally {
            try {
                if(httpclient != null) {
                    httpclient.close();
                }
            } catch (IOException e2) {
                rs = e2.getMessage();
                statusCode = -1;
            }
        }
        rsMap.put("statusCode",statusCode);
        if(statusCode == -1) {
            rsMap.put("msg",rs);
            rsMap.put("data",null);
        }
        else {
            rsMap.put("msg","success");
            rsMap.put("data",rs);
        }
        return rsMap;
    }
}
